package com.ufo.dis.service.controller;


import com.ufo.dis.service.common.utils.R;
import com.ufo.dis.service.entity.Mydir;
import com.ufo.dis.service.entity.Myfile;
import com.ufo.dis.service.service.HdfsService;
import org.apache.hadoop.fs.FileStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("hdfs/do")
public class HdfsController {
    @Autowired
    HdfsService hdfsService;


    //用户主页
    @RequestMapping("/list/{usr}")
    public R list(@RequestParam Map<String, Object> params, @PathVariable("usr") String usr) throws IOException {
        List<Myfile> files = new ArrayList<Myfile>();
        List<Mydir> dirs = new ArrayList<Mydir>();
        System.out.println(usr);
        String upath = "hdfs://localhost:9000/" + usr;
        FileStatus[] list = hdfsService.ls(usr);
        String currentpath = usr;
        if (list != null)
            for (int i = 0; i < list.length; i++) {
                if (list[i].isDir()) {
                    dirs.add(cd(list[i].getPath().getName(), i, list[i].getPath().getParent() + "/" + list[i].getPath().getName(), null, null));
                } else {

                    files.add(cm(list[i].getPath().getName(), i, upath + "/" + list[i].getPath().getName(), "http://123.57.56.140:8080/examples/hadooptmp/"  + "/" + list[i].getPath().getName()));
                }
            }
        return R.ok().put("dirdata", dirs).put("filedata", files).put("currentpath", currentpath);
    }


    //传入path
    @RequestMapping("/list/son")
    public R pathlist(@RequestBody HashMap<String, String> map) throws IOException {
        String path = map.get("url");
        path = path.replace("hdfs://localhost:9000/", "");
        List<Myfile> files = new ArrayList<>();
        List<Mydir> dirs = new ArrayList<>();
        FileStatus[] list = hdfsService.ls(path);
        String upath = path;
        path = path.replace("hdfs://localhost:9000", "");
        String currentpath = path;

        if (list != null)
            for (int i = 0; i < list.length; i++) {
                if (list[i].isDir()) {
                    dirs.add(cd(list[i].getPath().getName(), i, list[i].getPath().getParent() + "/" + list[i].getPath().getName(), null, null));
                } else {

                    files.add(cm(list[i].getPath().getName(), i, upath + "/" + list[i].getPath().getName(), "http://123.57.56.140:8080/examples/hadooptmp/"  + "/" + list[i].getPath().getName()));
                }
            }
        return R.ok().put("dirdata", dirs).put("filedata", files).put("currentpath", currentpath);
    }

    //mkdir
    @RequestMapping("/list/mkdir")
    public R mkdir(@RequestBody HashMap<String, String> map) throws IOException {
        String path = map.get("url");
        String newdir = map.get("newdir");
        path = path.replace("hdfs://localhost:9000", "");
        String currentpath = path;
        String nn = path + "/" + newdir;
        System.out.println(nn);
        if (hdfsService.mkdirs(nn)) {
            return R.ok().put("currentpath", currentpath);
        } else {
            return R.error("新建失败");
        }
    }

    //delete
    @RequestMapping("/list/delete")
    public R delete(@RequestBody HashMap<String, String> map) throws IOException {
        String path = map.get("url");
        path = path.replace("hdfs://localhost:9000", "");
        String currentpath = path;
        if (hdfsService.delete(path)) {
            return R.ok().put("currentpath", currentpath);
        } else {
            return R.error("新建失败");
        }
    }

    //upload
    @RequestMapping("/list/upload")
    public R upload(@RequestBody HashMap<String, String> map) throws IOException {
        String path = map.get("url");
        String filepath = map.get("filepath");
        if (hdfsService.upload1(path, filepath)) {
            return R.ok();
        } else {
            return R.error("上传失败");
        }
    }

    //upload2
    @RequestMapping("/list/upload2")
    public R upload2(@RequestParam(value = "path") String path, @RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, HttpServletResponse resp) throws IOException {
        if (request.getCharacterEncoding() == null) {
            request.setCharacterEncoding("UTF-8");
        }
        System.out.println(path);
        String fileName = file.getOriginalFilename();
        String filePath = "/usr/local/apache-tomcat-8.5.61/webapps/examples/hadooptmp/";
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            ServletOutputStream out = resp.getOutputStream();
            OutputStreamWriter ow = new OutputStreamWriter(out, "UTF-8");
            ow.write(filePath + fileName);
            ow.flush();
            ow.close();
            System.out.println("file:///" + filePath + fileName);
            System.out.println(path);
            hdfsService.upload1(path, "file:///" + filePath + fileName);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("上传失败");
        }
        return R.ok();
    }


    //mv
    @RequestMapping("/list/mv")
    public R mv(@RequestBody HashMap<String, String> map) throws IOException {
        String path = map.get("path");
        String newpath = map.get("newpath");
        if (hdfsService.mv(path, newpath)) {
            return R.ok();
        } else {
            return R.error("移动失败");
        }
    }


    public Myfile cm(String name, int id, String url, String downloadurl) {
        Myfile myfile = new Myfile();
        myfile.setName(name);
        myfile.setId(id);
        myfile.setUrl(url);
        myfile.setDownloadurl(downloadurl);
        return myfile;
    }


    public Mydir cd(String name, int i, String url, Object o, Object o1) {
        Mydir mydir = new Mydir();
        mydir.setName(name);
        mydir.setId(i);
        mydir.setUrl(url);
        return mydir;
    }
}

